package com.lx.db;

import com.lx.core.annotation.Bean;
import com.lx.util.LX;
import com.lx.core.LXLog;

import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Bean(init = "init")
public class LXRedis {
    /**  用来存储*/
    private static final Map<String,Object> DATA = new ConcurrentHashMap();

    /**  保存/更新数据*/
    public void put(String key, Object value){
        DATA.put(key, value);
    }
    /**  获取数据*/
    public <T>T get(String key){
        return (T) DATA.get(key);
    }
    /**  删除数据*/
    public void delete(String key){
        DATA.remove(key);
    }

    //说明: 初始化方法
    /**{ ylx } 2021/11/7 13:35 */
    public void init() throws IOException {
        new Thread(()->{
            File f = new File("LXRedis.rdb");
            try {
                if(!f.exists()) {
                    f.createNewFile();
                }else{
                    String data = loadRdb(f);
                    if (LX.isNotEmpty(data)){
                        Map<String, Object> stringObjectMap = LX.toMap(data);
                        DATA.putAll(stringObjectMap);
                    }
                }
            }catch (Exception e){
                LXLog.error("加载数据失败:",e);
            }
            //定时写入数据
            while (true){
                try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f),"utf-8"))){
                    pw.println(LX.toJSONString(DATA));
                } catch (Exception e) {
                }
                LX.sleep(5000);
            }
        }).start();
    }

    //说明:加载文件中的数据
    /**{ ylx } 2021/11/7 14:22 */
    private String loadRdb(File f) throws IOException {
        //读取之前存储的数据
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f),"utf-8"))){
            String line = null;
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        }
        return sb.toString();
    }
}
